package org.tongdao.yulong;

import org.tongdao.yulong.dao.DemoDao;
import org.tongdao.yulong.dao.impl.DemoDaoImpl;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Description: TODO
 * @author: 殷玉龙
 * @date: 2020年09月27日 3:30 下午
 */
public class BeanFactory {

  // 缓存区，保存已经创建好的对象
  private static Map<String,Object> beanMap = new HashMap<>();

  private static Properties properties;

  static {
    properties = new Properties();
    try {
      properties.load(BeanFactory.class.getClassLoader().getResourceAsStream("factory.properties"));
    } catch (IOException e) {
      e.printStackTrace();
      throw new RuntimeException("DemoDao instantiation error,cause : " + e.getMessage());
    }
  }

  public static Object getBean(String beanName){
    // 双检锁保证beanMap里没有对象才会创建
    if (!beanMap.containsKey(beanName)) {
      synchronized (BeanFactory.class) {
        if (!beanMap.containsKey(beanName)) {
          try {
            Class<?> beanClazz = Class.forName(properties.getProperty(beanName));
            Object bean = beanClazz.newInstance();
            //反射创建后放入缓存再返回
            beanMap.put(beanName,bean);
          } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException("BeanFactory have not [" + beanName + "] bean!",e);
          } catch (IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
            throw new RuntimeException("[" + beanName + "]" + " init error!!",e);
          }
        }
      }
    }
    return beanMap.get(beanName);


  }
}
